package com.feihong.txgw.ui.activity.base;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.feihong.txgw.R;
import com.feihong.txgw.app.App;
import com.feihong.txgw.message.ForceLogoutMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.user.User;
import com.feihong.txgw.ui.activity.user.LoginActivity;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.utils.CacheDataManger;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.ScreenUtil;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;
import com.feihong.txgw.utils.weakrefrence.StackTopActivity;
import com.xiaomi.mistatistic.sdk.MiStatInterface;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import cn.pedant.SweetAlert.SweetAlertDialog;
import me.yokeyword.fragmentation.SupportActivity;

import static com.feihong.txgw.ui.activity.user.LoginActivity.isFrouceLogoutKey;

/**
 * Created by Sabirjan on 2017/6/13.
 * TXGW.
 * 飞宏电子
 */

public abstract class BaseActivity extends SupportActivity {
    /**
     * activity因某些原因重启
     */
    public boolean isRestartActivity = false;
    public Unbinder unbinder;
    protected boolean isTransAnim = true;
    private SweetAlertDialog pDialog = null;

//    public ImmersionBar mImmersionBar;
    /**
     * 特定的状态栏view
     */
    private View mSpecificTitleLayout;
    /**
     * 默认的状态栏view
     */
    private View mDefaultTitleLayaout;
    /**
     * 状态栏字体颜色是否为深色 默认为深色
     */
    public boolean isDrakFont = true;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Log.i(TAG, "刘海屏: " + isInMultiWindowMode() + "  " + isInPictureInPictureMode() + " 状态栏高度  " + ScreenUtil.getStatusBarHeight(this));
        }
        if (savedInstanceState != null) {
            isRestartActivity = true;
        }
        windowStyle();
        setTheme();
        setContentView(setLayoutID());
        unbinder = ButterKnife.bind(this);
        initView(savedInstanceState);
        bindData();
        mDefaultTitleLayaout = findViewById(R.id.activity_status_layout);
        initImmersionBar();
//
    }
    /**
     * 设置全屏style
     */
    public void windowStyle() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 设置状态栏字体颜色
     */
    protected void initImmersionBar(){
        if(!ScreenUtil.setStatusBarDarkFont(this,isDrakFont)){
            if(mSpecificTitleLayout != null){
                mSpecificTitleLayout.setBackgroundColor(getResources().getColor(R.color.trans));
            }else if(mDefaultTitleLayaout != null){
                mDefaultTitleLayaout.setBackgroundColor(getResources().getColor(R.color.trans));
            }
        }
    }

    public void setSpecificTitleLayout(View view){
        mSpecificTitleLayout = view;
    }

    /**
     * 设置界面theme
     */
    public abstract void setTheme();

    /**
     * 设置布局id
     *
     * @return
     */
    public abstract int setLayoutID();

    /**
     * 启动activity
     * @param intent
     */
    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        if (isTransAnim) {
            getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }

    /**
     * activity在start的时候保存此activity的弱引用
     * 主要用于用户token失效时 启动强制退出弹窗
     * {@link com.feihong.txgw.utils.client.TxokttpClient.TxInterceptors #checkToken}
     */
    @Override
    protected void onStart() {
        super.onStart();
        StackTopActivity.getInstance().put(this);
    }

    @Override
    public void finish() {
        super.finish();
        if (isTransAnim) {
            getActivity().overridePendingTransition(R.anim.fade_in_from_left, R.anim.slide_in_left);
        }
    }

    public static final String TAG = "通讯顾问";

    /**
     * 获取用户ID
     * 2017.7.25
     * 张鹏
     *
     * @return
     */
    public String getUserId() {
        User userInfo = UserLoginInfo.getUserInfo();
        if (userInfo != null) {
            return userInfo.getUserID();
        } else {
            return null;
        }
    }

    /**
     * 绑定View
     */
    public abstract void initView(Bundle savedInstanceState);

    /**
     * 绑定数据
     */
    public abstract void bindData();


    /**
     * 用户登录退出 状态改变
     * @param loginMessage
     */
    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void doUserLogin(LoginMessage loginMessage) {
        onUserLogin(loginMessage);
    }

    /**
     * 用户登录状态改变时通知接口 ， 在页面里面需要通知，则onCreate事件里面必须注册EventBus
     *
     * @param loginMessage
     */
    public abstract void onUserLogin(LoginMessage loginMessage);

    /**
     * 设置页面标题
     *
     * @param title
     */
    public void setPageTitle(String title) {
        if (title != null) {
            TextView textView = (TextView) findViewById(R.id.txt_pagetitle);
            if (textView != null) {
                textView.setText(title);
            }
        }
    }

    public void setBackButtonFinish() {
        ImageView button = (ImageView) findViewById(R.id.btn_back);
        if (button != null) {
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    chackActivityState();
                    finish();
                }
            });
        }
    }

    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
//        if(mImmersionBar != null){
//            mImmersionBar.destroy();
//        }
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MiStatInterface.recordPageStart(this, this.getClass().getName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MiStatInterface.recordPageEnd();
    }

    @Override
    public boolean dispatchTrackballEvent(MotionEvent ev) {
        return super.dispatchTrackballEvent(ev);
    }

    public boolean activityIsDestory() {
        if (isFinishing()) {
            return true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (isDestroyed()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
        chackActivityState();
    }

    /**
     * 检查当前activity是否重启
     */
    public void chackActivityState() {
        if (isRestartActivity) {
            Intent intent = new Intent();
            intent.setAction("com.feihong.txgw.activity.HomeActivity");
            startActivity(intent);
        }
    }

    public boolean isUserLogin() {
        if (UserLoginInfo.isUserLogin()) {
            return true;
        }
        return false;
    }

    public void showProgressDialog(String message) {
        showProgressDialog(message, false);
    }

    /**
     * 进度弹窗
     * @param message
     * @param cancelable 是否响应返回键
     */
    public void showProgressDialog(String message, boolean cancelable) {
        if (pDialog != null) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText(message);
        pDialog.setCancelable(cancelable);
        pDialog.show();
    }

    public void dismissProgressDialog() {
        if (pDialog != null) {
            if (pDialog.isShowing()) {
                pDialog.dismissWithAnimation();
            }
            pDialog = null;
        }
    }

    /**
     * 展示弹窗
     * @param title
     * @param message
     * @param dismissListener
     */
    public void showDialog(String title, String message, DialogInterface.OnDismissListener dismissListener) {
        try {
            SweetAlertDialog dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.CUSTOM_IMAGE_TYPE);
            dialog.setTitleText(title);
            dialog.setContentText(message);
            dialog.setCancelable(false);
            dialog.setNeutralText("知道了");
            if (dismissListener != null) {
                dialog.setOnDismissListener(dismissListener);
            }
            dialog.show();
        } catch (Exception ex) {

        }
    }

    public void showDialog(String title, String message) {
        showDialog(title, message, null);
    }

    /**
     * 左右双按钮的弹窗
     * 相对于{@link #showDialog(String, String, DialogInterface.OnDismissListener)}只有一个按钮来说
     * @param title
     * @param message
     * @param confirmText
     * @param cancelText
     * @param confirmClickListener
     * @param cancelClickListener
     */
    public void showConfirmDialog(String title, String message, String confirmText, String cancelText, SweetAlertDialog.OnSweetClickListener confirmClickListener, SweetAlertDialog.OnSweetClickListener cancelClickListener) {
        SweetAlertDialog dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.CUSTOM_IMAGE_TYPE);
        dialog.setTitleText(title)
                .setContentText(message)
                .setConfirmText(confirmText).setCancelText(cancelText);
        if (confirmClickListener != null) {
            dialog.setConfirmClickListener(confirmClickListener);
        }

        if (cancelClickListener != null) {
            dialog.setCancelClickListener(cancelClickListener);
        }
        dialog.show();
    }

    public void showConfirmDialog(String title, String message, String confirmText, String cancelText, SweetAlertDialog.OnSweetClickListener confirmClickListener) {
        showConfirmDialog(title, message, confirmText, cancelText, confirmClickListener, null);
    }

    public void showSystemToast(String message) {
        try {
            ToastUtils.cannelToast();
            ToastUtils.getInstance().showShortToast(message);
        } catch (Exception ex) {

        }
    }
    /**
     * 跳往新的Activity
     * @param clz 要跳转的Activity
     * @param bundle bundel数据
     * @param requestCode requestCode
     */
    public void startNewActivityForResult(@NonNull Class<?> clz, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        if (isTransAnim) {
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        }
    }

    public void setResultActivity(int resultCode, Bundle bundleData) {
        Intent intent = new Intent();
        intent.putExtras(bundleData);
        setResult(resultCode, intent);
    }

    /**
     * 方法待删除
     * @param forceLogoutMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onForceLogoutMsg(ForceLogoutMessage forceLogoutMessage) {
        UserLoginInfo.userExitLogin();
        // 退出登录时  将默认收货地址的缓存清空
        PreferenceTools.putString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, "");
        PreferenceTools.putString("ll_info_result", "");
        //应该把我的->用户名称 还原
        try {
            CacheDataManger.getTotalCacheSize(getActivity()).startsWith("0");
        } catch (Exception e) {

        }
        LoginMessage loginMessage = new LoginMessage();
        loginMessage.setAction(LoginMessage.ACTION_EXIT);
        GreenDaoOperateHelper.delAll();
        EventBus.getDefault().post(loginMessage);
        UserLoginInfo.updateUserToken("");
        App.getApp().lastUpdateToken = 0;
        showDialog(null, "您的身份信息已失效,请重新登录", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.cancel();
                Intent intent = new Intent();
                intent.setClass(getActivity(), LoginActivity.class);
                intent.putExtra(isFrouceLogoutKey,true);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_MENU){

        }
        return super.onKeyDown(keyCode, event);
    }
}
